<template>
  <div >
    <div class="card-mark-draw-body-header" ref="drawheader">
      <a-form :form="form" :layout="formLayout" @submit="handleSubmit">
        <a-form-item
          label="卡片类型"
        >
          <a-tree-select
            v-decorator="['typeIds']"
            show-search
            style="width: 450px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择分类"
            allow-clear
            tree-default-expand-all
            :treeData="treeData"
            :treeCheckable="true"
            :maxTagCount="4"
            :replaceFields="replaceFields"
            :treeDefaultExpandAll="false"
            :getPopupContainer="()=>this.$refs.drawheader"
          >
            <a-icon slot="suffixIcon" type="loading" />
          </a-tree-select>
        </a-form-item>
        <a-form-item
          label="卡片名称"
        >
          <a-input
            v-decorator="['title']"
            placeholder="输入卡片名称查询" />
        </a-form-item>
        <a-form-item :wrapper-col="buttonItemLayout.wrapperCol">
          <a-button html-type="submit" type="primary" size="small" :loading="loading">
            搜索
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    <a-spin :spinning="loading" >
      <div class="card-mark-draw-body-content " ref="panel" @scroll="handscroll" >
        <waterfall
          :line-gap="WaterfallItemWidth"
          :watch="cards"
          class="waterfall"
          :align="'center'"
          ref="waterfall"
        >
          <!-- each component is wrapped by a waterfall slot -->
          <waterfall-slot
            v-for="(item, index) in cards"
            :width="item._width"
            :height="item._height + 79"
            :order="index"
            :key="item.id"
            class="p-xs"
          >
            <a-card
              draggable="true"
              @drag="drag"
              @dragstart="dragstart($event,item)"
              @dragend="dragend"
              unselectable="on"
              hoverable
              :bordered="false"
              class="card-mark-list-item">
              <img
                :width="item._width"
                :height="item._height"
                draggable="true"
                @dragstart="$event.preventDefault();$event.stopPropagation()"
                slot="cover"
                alt="example"
                :src="item.imgUrl"
              />
              <a-card-meta
                :title="item.title"
                draggable="true"
                @dragstart="$event.preventDefault();$event.stopPropagation()">
                <template slot="description">
                  {{ item.desc }}
                </template>
              </a-card-meta>
              <transition enter-active-class="animate__bounceIn" leave-active-class="animate__bounceOut" >
                <a-icon class="animate__animated card-actions drag" type="drag" />
              </transition>
            </a-card>
          </waterfall-slot>
        </waterfall>
      </div>
    </a-spin>
  </div>
</template>

<script>
import Waterfall from 'vue-waterfall/lib/waterfall'
import WaterfallSlot from 'vue-waterfall/lib/waterfall-slot'
import { Subject } from 'rxjs'
import { throttleTime } from 'rxjs/operators'
import { PortalEventBus } from './event'
import { getCardTypeTree, getCardListByPage } from '@/api/cardMarket'
import { PageClass } from '@/model/page.model'
import { mapGetters } from 'vuex'
import { getComponentName } from '@/utils/util'

const mockCards = [
 { 'x': 0, 'y': 0, 'w': 7, 'h': 4, 'i': '11', imgUrl: '/static/img/card01.png', name: '预警信息卡片01', desc: '展示预警信息' },
 { 'x': 17, 'y': 0, 'w': 7, 'h': 3, 'i': '12', imgUrl: '/static/img/card02.jpg', name: '预警信息卡片02', desc: '展示预警信息' },
 { 'x': 0, 'y': 1, 'w': 7, 'h': 2, 'i': '13', imgUrl: '/static/img/card03.jpg', name: '预警信息卡片03', desc: '展示预警信息' },
 { 'x': 17, 'y': 1, 'w': 7, 'h': 3, 'i': '14', imgUrl: '/static/img/card04.jpg', name: '预警信息卡片04', desc: '展示预警信息' },
 { 'x': 0, 'y': 2, 'w': 7, 'h': 4, 'i': '15', imgUrl: '/static/img/card05.jpg', name: '预警信息卡片05', desc: '展示预警信息' },
 { 'x': 7, 'y': 6, 'w': 10, 'h': 4, 'i': '16', imgUrl: '/static/img/card06.jpg', name: '预警信息卡片06', desc: '展示预警信息' },
 { 'x': 17, 'y': 6, 'w': 7, 'h': 4, 'i': '17', imgUrl: '/static/img/card07.jpg', name: '预警信息卡片07', desc: '展示预警信息' }
]
const WaterfallItemWidth = 265
function coverCardWidthAndHeight (cards) {
  const SLOTW = WaterfallItemWidth
  const _cards = cards.map(c => {
    const _width = SLOTW
    const _height = Math.ceil((Number(c.high) * Number(SLOTW) / Number(c.width)))
    return { ...c,
      i: c.id,
      w: c.width,
      h: c.high,
      name: c.title,
      componentName: getComponentName(c.moduleName),
      imgUrl: '/static/img/card01.png',
      _width,
      _height
    }
  })
  console.log(_cards)
  return _cards
}
const mouseXY = { 'x': null, 'y': null }
const handleDragOver = (e) => {
    mouseXY.x = e.clientX
    mouseXY.y = e.clientY
}
// eslint-disable-next-line no-unused-vars
let cardTransfer
const subject = new Subject()
export default {
  name: 'CardMarket',
  components: {
    Waterfall,
    WaterfallSlot
  },
  props: {
  },
  data () {
    return {
      formLayout: 'inline',
      formItemLayout: {},
      buttonItemLayout: {},
      treeExpandedKeys: [],
      value: undefined,
      cards: [],
      loading: false,
      WaterfallItemWidth,
      pageObj: new PageClass(),
      treeData: [],
      replaceFields: {
        title: 'name', key: 'id', value: 'id'
      },
      preLoad: false,
      form: this.$form.createForm(this),
      seacheObj: {
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'portalSetMenuId'])
  },
  mounted () {
    this.getCardTypeTree()
    document.addEventListener('dragover', handleDragOver, false)
    // this.getCards()
    subject.pipe(throttleTime(30)).subscribe({
      next: (v) => {
        PortalEventBus.$emit('drag', { mouseXY, cardTransfer })
      }
    })
    console.log(this.userInfo)
    this.handleSubmit()
  },
  methods: {
    handleChange (e) {
    },
    getCards () {
      this.loading = true
      setTimeout(() => {
        this.cards = [...this.cards, ...coverCardWidthAndHeight(mockCards)]
        this.loading = false
      }, 500)
    },
    handleSubmit (e) {
      console.log('handleSubmit')
      e && e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          this.pageObj = new PageClass()
          this.seacheObj = { ...values, menuId: this.portalSetMenuId, id: this.userInfo.id, current: this.pageObj.current, size: this.pageObj.size }
          this.getCardListByPage(true)
        }
      })
    },
    getCardListByPage (refreash = false) {
      if (refreash) {
        this.cards = []
      }
      this.loading = true
      getCardListByPage(this.seacheObj).then(({ code, data, msg }) => {
        if (code === 0) {
          console.dir(data)
          this.cards = [...this.cards, ...coverCardWidthAndHeight(Array.isArray(data.records) ? data.records : [])]
          this.pageObj.total = data.total
        }
      }).finally(() => { this.loading = false })
    },
    handscroll (e) {
      const panel = this.$refs.panel
      let scrollTop = 30; let maxScroll = 0
      scrollTop = panel.scrollTop
      maxScroll = panel.scrollHeight - panel.offsetHeight
      if (scrollTop >= maxScroll) {
        this.getNextPage()
      }
    },
    getNextPage () {
      if (this.loading) {
        return
      }
      console.log('加一页')
      this.pageObj.current += 1
      this.geCardListByPage()
    },
    // drag module start
    drag (e) {
      subject.next()
    },
    dragend (e) {
      PortalEventBus.$emit('dragend', { mouseXY, cardTransfer })
      cardTransfer = null
    },
    dragstart (e, item) {
      cardTransfer = item
    },
    // drag module end
    getCardTypeTree () {
      this.preLoad = true
      getCardTypeTree({}).then(({ code, msg, data }) => {
        if (code === 0) {
          this.treeData = data
        }
      }).finally(() => { this.preLoad = false })
    }
  },
  destroyed () {
    document.removeEventListener('dragover', handleDragOver, false)
  }
}
</script>
<style lang="less" scope>
.waterfall{
  overflow: visible !important;
}
.card-mark-list-item{
  position:absolute !important;
  top: 5px;
  left: 5px;
  right: 5px;
  bottom: 5px ;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  &:hover{
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transform: scale(1.05);
  }
}
</style>
